
package com.hlkj.pay.app.merchant.ext.impl.huifu.handler.params;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.HuiFuConfig;
import com.hlkj.pay.app.merchant.ext.impl.huifu.dto.access.*;
import com.hlkj.pay.app.merchant.ext.impl.huifu.utils.HuiFuUtil;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigAppIdDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigDto;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigListDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBusiAliRealnameApplyRequest;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBusiConfigRequest;
import com.huifu.bspay.sdk.opps.core.request.V2MerchantBusiRealnameRequest;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
public class HuiFuMerchantConfigParamsHandle extends HuiFuMerchantAccessCommonParamsHandle {

    /**
     * 微信配置参数
     * 
     * @param channelMerchantBusinessContext
     * @return
     */
    public static V2MerchantBusiConfigRequest v2MerchantBusiConfigRequest(HuiFuConfig huiFuConfig, ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        MerchantAccessBusinessDO merchantAccessScene = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessBusiness();
        PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(merchantAccessScene.getSceneType());
        MerchantWechatConfigDto merchantWechatConfigDto = channelMerchantBusinessContext.getMerchantWechatConfigDto();
        MerchantAccessAuthDO merchantAccessAuth = channelMerchantBusinessContext.getMerchantAccessAuth();
        JSONObject obj = JSONObject.parseObject(merchantAccessAuth.getChannelJson());
        V2MerchantBusiConfigRequest request = new V2MerchantBusiConfigRequest();
        // 请求流水号
        request.setReqSeqId(SequenceTools.getReqSeqId32());
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        // request.setHuifuId();
        // 01-标准费率线上（支持统一进件页面版）
        // 02-标准费率线下（支持统一进件页面版）
        request.setFeeType(obj.getString("feeType"));
        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();
        if (StringUtils.hasText(merchantWechatConfigDto.getJsAPIPath())) {
            extendInfoMap.put("wx_woa_path", merchantWechatConfigDto.getJsAPIPath());
        }
        if (StringUtils.hasText(merchantWechatConfigDto.getAppId())) {
            request.setWxWoaAppId(merchantWechatConfigDto.getAppId());
        }
        if (StringUtils.hasText(merchantAccessAuth.getSerialCode()))
            extendInfoMap.put("bank_channel_no", merchantAccessAuth.getSerialCode());
        request.setExtendInfo(extendInfoMap);
        return request;
    }

    /**
     * 微信认证参数
     * 
     * @param huiFuConfig
     * @param channelMerchantBusinessContext
     * @return
     */
    public static V2MerchantBusiRealnameRequest v2MerchantBusiRealnameRequest(HuiFuConfig huiFuConfig, ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        MerchantAccessDto merchantAccessDto = channelMerchantBusinessContext.getMerchantAccessDto();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessLegal();
        // 2.组装请求参数
        V2MerchantBusiRealnameRequest request = new V2MerchantBusiRealnameRequest();
        // 请求流水号
        request.setReqSeqId(SequenceTools.getReqSeqId32());
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        // 汇付ID
        // request.setHuifuId("6666000104854510");
        // 联系人姓名
        request.setName(merchantAccessContact.getName());
        // 联系人手机号
        request.setMobile(merchantAccessContact.getPhone());
        // 联系人身份证号码
        request.setIdCardNumber(merchantAccessContact.getCertNo());
        // 联系人类型
        request.setContactType("LEGAL");
        Map<String, Object> extendInfoMap = getWechatExtendInfos(huiFuConfig, channelMerchantBusinessContext);
        request.setExtendInfo(extendInfoMap);
        return request;
    }

    /**
     * 支付宝认证参数
     * 
     * @param huiFuConfig
     * @param channelMerchantBusinessContext
     * @return
     */
    public static V2MerchantBusiAliRealnameApplyRequest v2MerchantBusiAliRealnameApplyRequest(HuiFuConfig huiFuConfig,
            ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        // 2.组装请求参数
        V2MerchantBusiAliRealnameApplyRequest request = new V2MerchantBusiAliRealnameApplyRequest();
        // 请求流水号
        request.setReqSeqId(SequenceTools.getReqSeqId32());
        // 请求日期
        request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
        // 汇付ID
        // 主体信息
        request.setAuthIdentityInfo(getAuthIdentityInfo(channelMerchantBusinessContext.getMerchantAccessDto()));
        // 联系人信息
        request.setContactPersonInfo(getContactPersonInfo(channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessContact()));
        Map<String, Object> extendInfoMap = new HashMap<>();
        // 子渠道号
        extendInfoMap.put("pay_channel_id", huiFuConfig.getAlipayChannelId());
        // 01-标准费率线上（支持统一进件页面版）
        // 02-标准费率线下（支持统一进件页面版）
        // 支付场景
        extendInfoMap.put("pay_scene", "1");

        request.setExtendInfo(extendInfoMap);
        return request;
    }

    /**
     * 非必填字段
     * 
     * @return
     */
    private static Map<String, Object> getWechatExtendInfos(HuiFuConfig huiFuConfig, ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        MerchantAccessDto merchantAccessDto = channelMerchantBusinessContext.getMerchantAccessDto();
        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessCertInfoDO merchantAccessContact = merchantAccessDto.getMerchantAccessContact();
        MerchantAccessBusinessDO merchantAccessScene = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessLicenseDO merchantAccessLicense = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        PayEnums.SCENE_TYPE sceneType = PayEnums.SCENE_TYPE.from(merchantAccessScene.getSceneType());

        // 设置非必填字段
        Map<String, Object> extendInfoMap = new HashMap<>();
        // 子渠道号
        extendInfoMap.put("pay_channel_id", huiFuConfig.getWechatChannelId());
        // 01-标准费率线上（支持统一进件页面版）
        // 02-标准费率线下（支持统一进件页面版）
        // 支付场景
        switch (sceneType) {
            case OFFLINE:
                extendInfoMap.put("pay_scene", "02");
                break;
            case ONLINE:
                extendInfoMap.put("pay_scene", "01");
                break;
        }
        // 经营者/法人是否为受益人 企业开通微信支付时需要填写；Y：是最终受益人；N：非最终受益人(默认)；示例值：Y
        extendInfoMap.put("owner", "Y");

        // 法人证件居住地址
        extendInfoMap.put("identification_address", merchantAccessLegal.getAddress());
        extendInfoMap.put("name", merchantAccessContact.getName());
        extendInfoMap.put("mobile", merchantAccessContact.getPhone());
        extendInfoMap.put("id_card_number", merchantAccessContact.getCertNo());
        if (merchantAccessContact.getCertNo().equals(merchantAccessLegal.getCertNo())) {
            extendInfoMap.put("contact_type", "LEGAL");
        }
        else {
            extendInfoMap.put("contact_type", "SUPER");
            CommonResult<String> f28 = HuiFuUtil.fileUpload(merchantAccessContact.getCertBackUrl(), "联系人身份证正面照", "F28");
            CommonResult<String> f29 = HuiFuUtil.fileUpload(merchantAccessContact.getCertFrontUrl(), "联系人身份证反面照", "F29");
            List<Map<String, Object>> map = new ArrayList<>();
            Map<String, Object> f28Map = new HashMap<>();
            f28Map.put("file_type", "F28");
            f28Map.put("file_id", f28.getData());
            Map<String, Object> f29Map = new HashMap<>();
            f29Map.put("file_type", "F29");
            f29Map.put("file_id", f29.getData());
            map.add(f28Map);
            map.add(f29Map);
            // 文件列表
            extendInfoMap.put("special_file_info_list", JsonUtils.toJsonString(map));
        }
        // 联系人证件类型
        extendInfoMap.put("contact_id_doc_type", certType(merchantAccessContact.getCertType()));
        // 联系人证件有效期开始时间
        extendInfoMap.put("contact_period_begin", merchantAccessContact.getCertBeginDate());
        // 联系人证件有效期结束时间
        extendInfoMap.put("contact_period_end", merchantAccessContact.getCertEndDate());
        if (merchantAccessLicense != null) {
            // 证书类型
            extendInfoMap.put("cert_type", "CERTIFICATE_TYPE_2389");
            // 证书编号
            extendInfoMap.put("cert_number", merchantAccessLicense.getLicenseCode());
            // 证书照片
            // extendInfoMap.put("cert_copy", "");
        }
        else {
            CommonResult<String> f22 = HuiFuUtil.fileUpload(merchantAccessBusiness.getStoreHeaderUrl(), "门店门头照片", "F22");
            CommonResult<String> f24 = HuiFuUtil.fileUpload(merchantAccessBusiness.getStoreIndoorUrl(), "店内环境照片", "F24");
            CommonResult<String> f02 = HuiFuUtil.fileUpload(merchantAccessLegal.getCertFrontUrl(), "证件正面照", "F02");
            CommonResult<String> f03 = HuiFuUtil.fileUpload(merchantAccessLegal.getCertBackUrl(), "证件反面照", "F03");
            if (f22.isSuccess()) {
                // 门店门头照片
                extendInfoMap.put("store_header_copy", f22.getData());
            }
            if (f24.isSuccess()) {
                // 店内环境照片
                extendInfoMap.put("store_indoor_copy", f24.getData());
            }
            // 门店省市编码
            extendInfoMap.put("store_address_code", merchantAccessBusiness.getCityCode());
            // 门店地址
            extendInfoMap.put("store_address", merchantAccessBusiness.getAddress());
            if (f03.isSuccess()) {
                // 身份证件正面照片
                extendInfoMap.put("identification_front_copy", f02.getData());
            }
            if (f03.isSuccess()) {
                // 身份证件反面照片
                extendInfoMap.put("identification_back_copy", f03.getData());
            }
        }

        // 小微经营类型
        extendInfoMap.put("micro_biz_type", "MICRO_TYPE_STORE");
        // 门店名称
        extendInfoMap.put("store_name", merchantAccessBusiness.getShortName());
        //
        // // 单位证明函照片
        // extendInfoMap.put("company_prove_copy", "");
        // // 是否金融机构
        // extendInfoMap.put("finance_institution_flag", "N");
        // // 金融机构类型
        // extendInfoMap.put("finance_type", "");
        // // 特殊行业Id
        // extendInfoMap.put("category_id", "");
        // // 文件列表
        // extendInfoMap.put("special_file_info_list", getSpecialFileInfoList());
        return extendInfoMap;
    }

    /**
     * 主体信息
     * 
     * @param merchantAccessDto
     * @return
     */
    private static String getAuthIdentityInfo(MerchantAccessDto merchantAccessDto) {
        JSONObject dto = new JSONObject();
        MerchantAccessLicenseDO merchantAccessLicense = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        // 主体类型
        if (merchantAccessLicense != null) {
            dto.put("business_type", merchantAccessLicense.getCompanyType());
            // 证照类型
            dto.put("certificate_type", "BUSINESS_CERT");
            Map<String, Object> certificate_info = new HashMap<>();
            certificate_info.put("cert_type", "CERTIFICATE_TYPE_2389");
            certificate_info.put("cert_number", merchantAccessLicense.getLicenseCode());
            certificate_info.put("cert_merchant_name", merchantAccessLicense.getName());
            certificate_info.put("cert_legal_person", merchantAccessLegal.getName());
            certificate_info.put("cert_company_address", merchantAccessLicense.getAddress());
            certificate_info.put("effect_time", HuiFuUtil.date(merchantAccessLicense.getLicenseBeginDate()));
            certificate_info.put("expire_time", HuiFuUtil.date(merchantAccessLicense.getLicenseEndDate()));
            dto.put("certificate_info", JsonUtils.toJsonString(certificate_info));
        }
        else {
            dto.put("business_type", "1");
        }
        CommonResult<String> f02 = HuiFuUtil.fileUpload(merchantAccessLegal.getCertFrontUrl(), "证件正面照", "F02");
        CommonResult<String> f03 = HuiFuUtil.fileUpload(merchantAccessLegal.getCertBackUrl(), "证件反面照", "F03");
        if (f03.isSuccess()) {
            dto.put("card_front_img", f03.getData());
        }
        if (f02.isSuccess()) {
            dto.put("card_back_img", f02.getData());
        }
        return dto.toJSONString();
    }

    /**
     * 联系人
     * 
     * @param merchantAccessCertInfoDO
     * @return
     */
    private static String getContactPersonInfo(MerchantAccessCertInfoDO merchantAccessCertInfoDO) {
        JSONObject dto = new JSONObject();
        // 联系人姓名
        dto.put("name", merchantAccessCertInfoDO.getName());
        // 联系人手机号
        dto.put("mobile", merchantAccessCertInfoDO.getPhone());
        // 联系人身份证号码
        dto.put("id_card_number", merchantAccessCertInfoDO.getCertNo());
        return dto.toJSONString();
    }

    // private static String getUboInfoList(List<MerchantAccessCertInfoDO>
    // merchantAccessCertInfoList) {
    //
    // JSONArray dtoList = new JSONArray();
    // merchantAccessCertInfoList.stream().forEach(merchantAccessCertInfoDO -> {
    // JSONObject dto = new JSONObject();
    // // 受益人证件类型
    // dto.put("ubo_id_doc_type", "00");
    // HuiFuUtil.fileUpload(merchantAccessCertInfoDO.getCertBackUrl(), "");
    // // 证件正面照片
    // dto.put("ubo_id_doc_copy", "c7faf0e6-39e9-3c35-9075-2312ad6f4ea4");
    // // 受益人证件姓名
    // dto.put("ubo_id_doc_name", "杨雷");
    // // 受益人证件号码
    // dto.put("ubo_id_doc_number", "110101199003072631");
    // // 证件居住地址
    // dto.put("ubo_id_doc_address", "上海市徐汇区宜山路789号");
    // // 证件有效期开始时间
    // dto.put("ubo_period_begin", "19900307");
    // // 证件有效期结束时间
    // dto.put("ubo_period_end", "长期");
    // // 证件反面照片
    // dto.put("ubo_id_doc_copy_back", "c7faf0e6-39e9-3c35-9075-2312ad6f4ea4");
    // dtoList.add(dto);
    // });
    //
    // return dtoList.toJSONString();
    // }

    private static String getSpecialFileInfoList() {
        JSONObject dto = new JSONObject();
        // 文件类型
        dto.put("file_type", "F33");
        // 文件jfileID
        dto.put("file_id", "49ac7d9b-851c-31b4-8b21-2983ea97b98c");

        JSONArray dtoList = new JSONArray();
        dtoList.add(dto);
        return dtoList.toJSONString();
    }

    /**
     * 微信认证查询返回
     * 
     * @param response
     * @param merchantAccessAuthDO
     */
    public static void wechatAuthQueryParamsProcess(Map<String, Object> response, MerchantAccessAuthDO merchantAccessAuthDO) {
        HuiFuWechatAuthQueryDto huiFuWechatAuthQueryDto = JSONObject.parseObject(response.toString(), HuiFuWechatAuthQueryDto.class);
        if (huiFuWechatAuthQueryDto.isSuccess()) {
            if ("1".equals(huiFuWechatAuthQueryDto.getApplyment_stat())) {
                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
            }
            else {
                merchantAccessAuthDO.setStatus(wechatStatus(huiFuWechatAuthQueryDto.getApplyment_stat()).getCode());
            }
            merchantAccessAuthDO.setSerialCode(huiFuWechatAuthQueryDto.getPay_channel_id());
            if (StringUtils.hasText(huiFuWechatAuthQueryDto.getQrcode_data())) {
                merchantAccessAuthDO.setQrCodeArray(Base64Decoder.decode(huiFuWechatAuthQueryDto.getQrcode_data()));
            }
        }
        else {
            merchantAccessAuthDO.setRejectReason(huiFuWechatAuthQueryDto.getReject_reason());
            merchantAccessAuthDO.setRejectParam(huiFuWechatAuthQueryDto.getReject_param());
        }
    }

    public static MerchantEnum.MERCHANT_AUTH_STATUS wechatStatus(String wechatStatus) {
        if (!StringUtils.hasText(wechatStatus)) {
            return MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY;
        }
        switch (wechatStatus) {
            case "APPLYMENT_STATE_EDITTING":
                return MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING;
            case "APPLYMENT_STATE_WAITTING_FOR_AUDIT":
                return MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING;
            case "APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT":
                return MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM;
            case "APPLYMENT_STATE_WAITTING_FOR_CONFIRM_LEGALPERSON":
                return MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH;
            case "APPLYMENT_STATE_PASSED":
                return MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE;
            case "APPLYMENT_STATE_REJECTED":
                return MerchantEnum.MERCHANT_AUTH_STATUS.REJECT;
            case "APPLYMENT_STATE_FREEZED":
                return MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN;
            case "APPLYMENT_STATE_CANCELED":
                return MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL;
            case "APPLYMENT_STATE_NOAPPLY":
                return MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY;
            default:
                return MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY;
        }
    }

    /**
     * 支付宝查询返回
     * 
     * @param response
     * @param merchantAccessAuthDO
     */
    public static void alipayAuthQueryParamsProcess(Map<String, Object> response, MerchantAccessAuthDO merchantAccessAuthDO) {
        HuiFuAlipayAuthQueryDto parseObjectData = JSONObject.parseObject(response.toString(), HuiFuAlipayAuthQueryDto.class);
        if (parseObjectData.isSuccess()) {
            if ("AUTHORIZED".equals(parseObjectData.getAuthorize_stat())) {
                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
            }
            else {
                merchantAccessAuthDO.setStatus(alipayStatus(parseObjectData.getOrder_status()).getCode());
            }
//            merchantAccessAuthDO.setSerialCode(parseObjectData.getPay_channel_id());
            if (StringUtils.hasText(parseObjectData.getQrcode())) {
                merchantAccessAuthDO.setAuthUrl(parseObjectData.getQrcode());
            }
        }
        else {
            merchantAccessAuthDO.setRejectReason(parseObjectData.getReject_reason());
        }
    }

    public static MerchantEnum.MERCHANT_AUTH_STATUS alipayStatus(String alipayStatus) {
        // 审核中(AUDITING)
        // 待联系人确认(CONTACT_CONFIRM)
        // 待法人确认(LEGAL_CONFIRM)
        // 审核通过(AUDIT_PASS)
        // 审核失败(AUDIT_REJECT)
        // 已冻结(AUDIT_FREEZE)本次申请冻结但仍会返回上次的授权码，可以扫码授权。
        // 已撤回(CANCELED)
        // 未申请(NOT_APPLY)
        switch (alipayStatus) {
            case "AUDITING":
                return MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING;
            case "CONTACT_CONFIRM":
                return MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM;
            case "LEGAL_CONFIRM":
                return MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH;
            case "AUDIT_PASS":
                return MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE;
            case "AUDIT_REJECT":
                return MerchantEnum.MERCHANT_AUTH_STATUS.REJECT;
            case "AUDIT_FREEZE":
                return MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN;
            case "CANCELED":
                return MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL;
            default:
                return MerchantEnum.MERCHANT_AUTH_STATUS.NO_APPLY;
        }
    }

    /**
     * 微信参数配置
     *
     * @param response
     * @param channelMerchantBusinessContext
     */
    public static void businessOpenProcess(Map<String, Object> response, ChannelMerchantAccessContext channelMerchantBusinessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantBusinessContext.setRemark("产品开通参数配置返回信息为空");
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
            return;
        }
        HuiFuMerchantResponseDto huiFuMerchantResponseDto = JSONObject.parseObject(response.toString(), HuiFuMerchantResponseDto.class);
        if (huiFuMerchantResponseDto.isSuccess()) {
            String applyNo = huiFuMerchantResponseDto.getApply_no();
            if (applyNo != null) {
                MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
                merchantAccessInfo.setApplyNo(applyNo);
            }
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
        }
        else if (huiFuMerchantResponseDto.isDoing()) {
        }
        else {
            String respDesc = huiFuMerchantResponseDto.getResp_desc();
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantBusinessContext.setLastAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_WAIT_APPROVE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantBusinessContext.setRemark(respDesc);
            }
            else {
                channelMerchantBusinessContext.setRemark("产品开通参数配置返回错误信息为空,错误码为:" + huiFuMerchantResponseDto.getResp_code());
            }
        }
    }

    /**
     * 微信参数配置
     *
     * @param response
     * @param channelMerchantBusinessContext
     */
    public static void wechatConfigParamsProcess(Map<String, Object> response, ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        if (CollectionUtils.isEmpty(response)) {
            channelMerchantBusinessContext.setRemark("斗拱微信参数配置返回信息为空");
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
            return;
        }
        HuiFuMerchantResponseDto huiFuMerchantResponseDto = JSONObject.parseObject(response.toString(), HuiFuMerchantResponseDto.class);
        if (huiFuMerchantResponseDto.isSuccess()) {
            // channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_AUTH);
        }
        else if (huiFuMerchantResponseDto.isDoing()) {
        }
        else {
            String respDesc = huiFuMerchantResponseDto.getResp_desc();
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            if (StringUtils.hasText(respDesc)) {
                channelMerchantBusinessContext.setRemark(respDesc);
            }
            else {
                channelMerchantBusinessContext.setRemark("斗拱微信参数配置返回错误信息为空,错误码为:" + huiFuMerchantResponseDto.getResp_code());
            }
        }
    }

    /**
     * 微信认证
     *
     * @param response
     * @param merchantAccessAuthDO
     */
    public static void wechatAuthParamsProcess(Map<String, Object> response, MerchantAccessAuthDO merchantAccessAuthDO) {
        if (CollectionUtils.isEmpty(response)) {
            merchantAccessAuthDO.setRejectReason("斗拱微信认证返回信息为空");
            return;
        }
        HuiFuAuthResultDto huiFuMerchantResponseDto = JSONObject.parseObject(response.toString(), HuiFuAuthResultDto.class);
        if (!huiFuMerchantResponseDto.isSuccess()) {
            merchantAccessAuthDO.setRejectReason(huiFuMerchantResponseDto.getResp_desc());
            ;
        }
        // else if (huiFuMerchantResponseDto.isDoing()) {
        // }
        // else {
        // String respDesc = huiFuMerchantResponseDto.getResp_desc();
        // channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
        // if (StringUtils.hasText(respDesc)) {
        // channelMerchantBusinessContext.setRemark(respDesc);
        // }
        // else {
        // channelMerchantBusinessContext.setRemark("斗拱微信认证返回错误信息为空,错误码为:" +
        // huiFuMerchantResponseDto.getResp_code());
        // }
        // }
    }

    /**
     * 支付宝认证
     *
     * @param response
     * @param merchantAccessAuthDO
     */
    public static void alipayAuthParamsProcess(Map<String, Object> response, MerchantAccessAuthDO merchantAccessAuthDO) {
        if (CollectionUtils.isEmpty(response)) {
            merchantAccessAuthDO.setRejectReason("斗拱支付宝认证返回信息为空");
            return;
        }
        HuiFuAuthResultDto huiFuMerchantResponseDto = JSONObject.parseObject(response.toString(), HuiFuAuthResultDto.class);
        if (!huiFuMerchantResponseDto.isSuccess()) {
            merchantAccessAuthDO.setRejectReason(huiFuMerchantResponseDto.getResp_desc());
        }
    }

    public static void subAuthQueryParamsProcess(Map<String, Object> atuResponse, ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext) {
        if (CollectionUtils.isEmpty(atuResponse)) {
            return;
        }
        List<MerchantAccessAuthDO> merchantAccessAuthDbList = channelMerchantBusinessContext.getMerchantAccessAuthDbList();
        Map<String, MerchantAccessAuthDO> authMap = merchantAccessAuthDbList.stream().collect(Collectors.toMap(auth -> auth.getSubMchId(), Function.identity(), (t1, t2) -> t1));

        HuiFuSubAuthResultDto aliResponseDto = JsonUtils.parseObject(atuResponse.toString(), HuiFuSubAuthResultDto.class);
        List<MerchantAccessAuthDO> merchantAccessAuthList = new LinkedList<>();
        if (aliResponseDto.isSuccess()) {
            List<HuiFuSubAuthList> huiFuSubAuthLists = JsonUtils.parseArray(aliResponseDto.getMer_reg_info_list(), HuiFuSubAuthList.class);
            huiFuSubAuthLists.stream().forEach(huiFuSubAuthList -> {
                if ("U".equals(huiFuSubAuthList.getChannel_type())) {
                    MerchantAccessAuthDO merchantAccessAuthDO = authMap.get(huiFuSubAuthList.getBank_mer_code());
                    if (merchantAccessAuthDO == null) merchantAccessAuthDO = new MerchantAccessAuthDO();
                    if ("A".equals(huiFuSubAuthList.getPay_way())) {
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                    } else if ("W".equals(huiFuSubAuthList.getPay_way())) {
                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                    }
                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                    merchantAccessAuthDO.setSubMchId(huiFuSubAuthList.getBank_mer_code());
                    merchantAccessAuthDO.setMchId(huiFuSubAuthList.getBank_channel_no());
                    Map<String, String> channelJson;
                    if (StringUtils.hasText(merchantAccessAuthDO.getChannelJson())) {
                        channelJson = JsonUtils.parseObject(merchantAccessAuthDO.getChannelJson(), Map.class);
                    } else {
                        channelJson = new HashMap<>();
                    }
                    channelJson.put("feeType", huiFuSubAuthList.getFee_type());
                    merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(channelJson));
                    merchantAccessAuthList.add(merchantAccessAuthDO);
                }
            });
        }

        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessInfo();
        merchantAccessAuthList.stream().forEach(merchantAccessAuthDO -> {
            merchantAccessAuthDO.setSn(merchantAccessInfo.getSn());
            merchantAccessAuthDO.setAccessId(merchantAccessInfo.getId());
        });
        channelMerchantBusinessContext.setMerchantAccessAuthDbList(merchantAccessAuthList);

    }

    public static void wechatConfigQueryParamsProcess(Map<String, Object> response, ChannelMerchantAccessAuthQueryContext channelMerchantBusinessContext) {
        if (CollectionUtils.isEmpty(response)) {
            return;
        }
        HuiFuSubAuthResultDto aliResponseDto = JsonUtils.parseObject(response.toString(), HuiFuSubAuthResultDto.class);
        MerchantWechatConfigListDto merchantWechatConfigListDto = new MerchantWechatConfigListDto();
        List<String> jsApiPath = new ArrayList<>();
        List<MerchantWechatConfigAppIdDto> appIdList = new ArrayList<>();
        if (aliResponseDto.isSuccess()) {
            List<HuiFuSubAuthResultDto.WxConfig> huiFuSubAuthLists = JsonUtils.parseArray(aliResponseDto.getAtu_config_bo_list(), HuiFuSubAuthResultDto.WxConfig.class);
            huiFuSubAuthLists.stream().forEach(huiFuSubAuthList -> {
                if (!CollectionUtils.isEmpty(huiFuSubAuthList.getWx_config_list())) {
                    List<HuiFuSubAuthResultDto.WxConfig.WxConfigListBean> wxConfigList = huiFuSubAuthList.getWx_config_list();
                    wxConfigList.stream().forEach(wxConfigListBean -> {
                        if ("3".equals(wxConfigListBean.getConfig_type())) {
                            jsApiPath.add(wxConfigListBean.getConfig_value());
                        }
                        else {
                            MerchantWechatConfigAppIdDto merchantWechatConfigAppIdDto = new MerchantWechatConfigAppIdDto();
                            merchantWechatConfigAppIdDto.setSubAppid(wxConfigListBean.getConfig_value());
                            appIdList.add(merchantWechatConfigAppIdDto);
                        }
                    });
                }
            });
        }
        merchantWechatConfigListDto.setAppIdList(appIdList);
        merchantWechatConfigListDto.setJsApiPath(jsApiPath);
        channelMerchantBusinessContext.setMerchantWechatConfigListDto(merchantWechatConfigListDto);
    }
}
